package org.sky.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.sky.model.Person;
import org.sky.model.RoomUsed;
import org.sky.service.FileUtilService;
import org.sky.service.PersonService;
import org.sky.service.RoomUsedService;
import org.sky.util.ChangeTime;
import org.sky.util.ExcelUtil;
import org.sky.vo.FileVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Component("file")
@Scope("prototype")
public class FileAction extends MyActionSupport implements ModelDriven<FileVO> {

    @Qualifier("excelUtil")
    @Autowired
    private ExcelUtil excelUtil;
    //当前登录用户
    private HttpServletRequest request = ServletActionContext.getRequest();
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    private final FileVO fileVO = new FileVO();
    private FileUtilService fileUtilService;
    private PersonService personService;
    private final String username = userDetails.getUsername();
    private RoomUsedService roomUsedService;
    private final static Logger logger = Logger.getLogger(FileAction.class);
    private final static ChangeTime changeTime = new ChangeTime();
    private List<RoomUsed> rus = new ArrayList<RoomUsed>();
    private List<Object> obj = new ArrayList<Object>();
    private List<Person> ps = new ArrayList<Person>();
    private static String saveExcelPathDirByRoomUsed = "/file/roomUsed/";
    private static String saveExcelPathDirByPerson = "/file/person/";

    public String uploadFile() throws Exception {
        /** 构建保存的目录 **/
        String musicPathDir = "/file/music/";
        /** 得到保存目录的真实路径 **/
        String saveFilePathDir = request.getSession().getServletContext().getRealPath(musicPathDir);
        // 得到保存上传文件的目录的真实路径
        File dir = new File(saveFilePathDir);
        // 如果该目录不存在，就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        fileVO.setAuthor(username);

        DecimalFormat df = new DecimalFormat("0.00");
        fileVO.setSize(Double.parseDouble(df.format(fileVO.getUpload().length() / 1024.0 / 1024.0)));  // 文件大小(Mb计算)

        int pos = fileVO.getUploadFileName().trim().lastIndexOf(".");
        fileVO.setUploadContentType(fileVO.getUploadFileName().substring(pos + 1));//文件后缀名
        fileVO.setDate(new Date());//当前日期
        //构造名字
        String name = UUID.randomUUID().toString() + pos + "." + fileVO.getUploadFileName().substring(pos + 1);
        FileInputStream is = new FileInputStream(fileVO.getUpload());
        FileOutputStream os = new FileOutputStream(new File(dir, name));
        byte[] buf = new byte[1024];
        int len = -1;
        while ((len = is.read(buf)) != -1) {
            os.write(buf, 0, len);
        }

        is.close();
        os.close();
        fileVO.setUploadDir((musicPathDir + name));//保存路径

        if (fileUtilService.uploadFile(fileVO)) {
            fileVO.setResultMessage("{suc:1, msg:’上传成功!’}");
            logger.trace("User:" + username + "upload a file(" + fileVO.getUploadFileName() + ").");
        } else {
            fileVO.setResultMessage("{suc:0, msg:’上传失败!’}");
        }
        view = "/page/file/message.jsp";
        return VIEW;
    }

    public String createExcelByRoomUsed() {

        /** 得到保存目录的真实路径 **/
        String saveFilePathDir = request.getSession().getServletContext().getRealPath(saveExcelPathDirByRoomUsed);
        // 得到备份文件的目录的真实路径
        File dir = new File(saveFilePathDir);
        // 如果该目录不存在，就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        rus = roomUsedService.allRoomUsed();
        if (rus.size() <= 0) {
            fileVO.setResultMessage("<script>alert('房间使用信息为空！');location.href='/page/file/DateOperation.jsp';</script>");
            return ERROR;
        }
        String date = changeTime.formatDate(changeTime.getCurrentDate());
        //使用于07以上的版本，03以下的可以修改参数
        excelUtil.exportExcelByPath(saveFilePathDir + "/" + date + ".xlsx",
                rus, RoomUsed.class, true, date + " 房间使用信息 ");
        fileVO.setResultMessage("<script>alert('成功备份房间使用记录文件！文件名为" + date + ".xlxs');location.href='/page/file/DateOperation.jsp';</script>");
        logger.trace("User:" + username + " backup room used records success,file name is " + date);
        return SUCCESS;
    }

    public String recoverExcelByRoomUsed() {
        try {
            /** 得到保存目录的真实路径 **/
            String saveFilePathDir = request.getSession().getServletContext().getRealPath(saveExcelPathDirByRoomUsed);
            obj = excelUtil.readExcelByPath(saveFilePathDir + "/" + fileVO.getExcelFileName(),
                    RoomUsed.class, 1, 0);
            for (int i = 0; i < obj.size(); i++) {
                rus.add((RoomUsed) obj.get(i));
            }
            for (RoomUsed roomUsed : rus) {
                roomUsed.setId(0);
                roomUsedService.save(roomUsed);
            }
        } catch (NullPointerException e) {
            fileVO.setResultMessage("<script>alert('要读取的Excel文件的格式不正确，请检查');location.href='/page/file/DateOperation.jsp';</script>");
            return ERROR;
        }
        fileVO.setResultMessage("<script>alert('成功还原房间使用信息，请查看数据库');location.href='/page/file/DateOperation.jsp';</script>");
        logger.trace("User:" + username + " recover the room used records success");
        return SUCCESS;
    }

    public String createExcelByPerson() {
        /** 得到保存目录的真实路径 **/
        String saveFilePathDir = request.getSession().getServletContext().getRealPath(saveExcelPathDirByPerson);
        // 得到备份文件的目录的真实路径
        File dir = new File(saveFilePathDir);

        // 如果该目录不存在，就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }

        ps = personService.allPerson();
        if (ps.size() <= 0) {
            fileVO.setResultMessage("<script>alert('用户资料信息为空！');location.href='/page/file/DateOperation.jsp';</script>");
            logger.error("Person records is empty!");
            return ERROR;
        }
        String date = changeTime.formatDate(changeTime.getCurrentDate());
        //使用于07以上的版本，03以下的可以修改参数
        excelUtil.exportExcelByPath(saveFilePathDir + "/" + date + ".xlsx",
                ps, Person.class, true, date + " 用户资料 ");
        fileVO.setResultMessage("<script>alert('成功备份用户资料记录文件！文件名为" + date + ".xlxs');location.href='/page/file/DateOperation.jsp';</script>");
        logger.trace("User:" + username + " backup the Person records success! file name is " + date);
        return SUCCESS;
    }


    @Resource(name = "roomUsedServiceImpl")
    public void setRoomUsedService(RoomUsedService roomUsedService) {
        this.roomUsedService = roomUsedService;
    }


    @Resource(name = "fileUtilServiceImpl")
    public void setFileUtilService(FileUtilService fileUtilService) {
        this.fileUtilService = fileUtilService;
    }

    @Resource(name = "personServiceImpl")
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }

    @Override
    public FileVO getModel() {
        return fileVO;
    }

}
